#!/usr/bin/env python
#coding:utf-8

from main.units.interfaces import Backup
import time
import pyodbc

class SqlServerBackup(Backup):
    """ backup sqlserver database
        需要配置odbc for linux， 参见 http://my.oschina.net/pp219/blog/550331
        程序的自动化配置也需要在安装驱动之后才能进行，修改 /etc/odbc.ini 即可连接不同的数据源

        for windows, 只需要配置odbc数据源即可

    """
    name = 'sqlserver-backup'
    desc = 'sqlserver backup'

    def __init__(self, *args, **kwargs):
        super(SqlServerBackup, self).__init__(*args, **kwargs)

    def execute(self):
        try:
            dsn = self.kwargs.get('dsn')
            uid = self.kwargs.get('uid')
            pwd = self.kwargs.get('pwd')
            db = self.kwargs.get('db')
            output = self.kwargs.get('output')

            cnx = pyodbc.connect('dsn={};uid={};pwd={};TrustedConnection=Yes'.format(dsn, uid, pwd), autocommit=True)
        except Exception as exception:
            print ("Unexpected error:", exception.message)
        else:
            cur = cnx.cursor()
            cmdline = "backup database {} to disk = '{}'".format(db, output +'\\' + db +'_'+ str(time.time()) +'.bak')
            result  = cur.execute(cmdline)
            while cur.nextset(): pass
            cur.close()
            cnx.close()
            return result
